"""
KidsBuddy 1.0 用户模型
定义儿童用户和家长用户的数据模型，支持自我调节学习(SRL)功能
"""

import uuid
from abc import ABC, abstractmethod
from datetime import datetime
from typing import Dict, List, Optional, Any, Union
from dataclasses import dataclass, field
from enum import Enum


class LearningStyle(Enum):
    """学习风格枚举"""
    VISUAL = "visual"           # 视觉型学习者
    AUDITORY = "auditory"       # 听觉型学习者
    KINESTHETIC = "kinesthetic" # 动觉型学习者
    READING_WRITING = "reading_writing"  # 读写型学习者
    MULTIMODAL = "multimodal"   # 多模态学习者


class SRLLevel(Enum):
    """自我调节学习(SRL)水平枚举"""
    BEGINNER = "beginner"       # 初学者：需要大量外部指导
    DEVELOPING = "developing"   # 发展中：开始具备基本自我调节能力
    PROFICIENT = "proficient"   # 熟练：具备较好的自我调节能力
    ADVANCED = "advanced"       # 高级：具备优秀的自我调节学习能力


class Grade(Enum):
    """年级枚举"""
    PRESCHOOL = "preschool"     # 学前班
    GRADE_1 = "grade_1"         # 一年级
    GRADE_2 = "grade_2"         # 二年级
    GRADE_3 = "grade_3"         # 三年级
    GRADE_4 = "grade_4"         # 四年级
    GRADE_5 = "grade_5"         # 五年级
    GRADE_6 = "grade_6"         # 六年级
    GRADE_7 = "grade_7"         # 七年级
    GRADE_8 = "grade_8"         # 八年级
    GRADE_9 = "grade_9"         # 九年级


class UserRole(Enum):
    """用户角色枚举"""
    CHILD = "child"             # 儿童用户
    PARENT = "parent"           # 家长用户
    TEACHER = "teacher"         # 教师用户
    ADMIN = "admin"             # 管理员用户


class BaseUser(ABC):
    """用户基础抽象类

    定义所有用户类型的通用接口和行为，确保一致性和可扩展性
    """

    @abstractmethod
    def get_id(self) -> str:
        """获取用户唯一标识符"""
        pass

    @abstractmethod
    def get_name(self) -> str:
        """获取用户姓名"""
        pass

    @abstractmethod
    def get_role(self) -> UserRole:
        """获取用户角色"""
        pass

    @abstractmethod
    def get_created_at(self) -> datetime:
        """获取创建时间"""
        pass

    @abstractmethod
    def get_updated_at(self) -> datetime:
        """获取最后更新时间"""
        pass

    @abstractmethod
    def get_is_active(self) -> bool:
        """获取是否为活跃用户"""
        pass

    @abstractmethod
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式

        Returns:
            包含用户所有信息的字典
        """
        pass

    @classmethod
    @abstractmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'BaseUser':
        """从字典创建用户实例

        Args:
            data: 包含用户信息的字典

        Returns:
            用户实例
        """
        pass

    @abstractmethod
    def validate(self) -> bool:
        """验证用户数据的有效性

        Returns:
            数据是否有效

        Raises:
            ValidationError: 数据验证失败时抛出
        """
        pass

    @abstractmethod
    def update_timestamp(self):
        """更新最后修改时间戳"""
        pass

    def get_basic_info(self) -> Dict[str, Any]:
        """获取用户基本信息

        Returns:
            包含基本信息的字典
        """
        return {
            "id": self.get_id(),
            "name": self.get_name(),
            "role": self.get_role().value,
            "created_at": self.get_created_at().isoformat(),
            "updated_at": self.get_updated_at().isoformat(),
            "is_active": self.get_is_active()
        }

    def __str__(self) -> str:
        """字符串表示"""
        return f"{self.__class__.__name__}(id={self.get_id()}, name={self.get_name()})"

    def __repr__(self) -> str:
        """详细字符串表示"""
        return f"{self.__class__.__name__}(id='{self.get_id()}', name='{self.get_name()}', role='{self.get_role().value}')"

    def __eq__(self, other) -> bool:
        """相等性比较"""
        if not isinstance(other, BaseUser):
            return False
        return self.get_id() == other.get_id() and self.get_role() == other.get_role()

    def __hash__(self) -> int:
        """哈希值计算"""
        return hash((self.get_id(), self.get_role().value))


@dataclass
class LearningPreferences:
    """学习偏好设置"""
    preferred_study_time: Optional[str] = None  # 偏好学习时间，如 "morning", "afternoon", "evening"
    session_duration_minutes: int = 30          # 单次学习时长（分钟）
    break_interval_minutes: int = 5             # 休息间隔（分钟）
    difficulty_preference: str = "adaptive"     # 难度偏好：easy, medium, hard, adaptive
    feedback_frequency: str = "normal"          # 反馈频率：low, normal, high
    motivation_style: str = "encouragement"    # 激励方式：encouragement, achievement, social
    language_preference: str = "zh-CN"         # 语言偏好
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            "preferred_study_time": self.preferred_study_time,
            "session_duration_minutes": self.session_duration_minutes,
            "break_interval_minutes": self.break_interval_minutes,
            "difficulty_preference": self.difficulty_preference,
            "feedback_frequency": self.feedback_frequency,
            "motivation_style": self.motivation_style,
            "language_preference": self.language_preference
        }
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'LearningPreferences':
        """从字典创建实例"""
        return cls(
            preferred_study_time=data.get("preferred_study_time"),
            session_duration_minutes=data.get("session_duration_minutes", 30),
            break_interval_minutes=data.get("break_interval_minutes", 5),
            difficulty_preference=data.get("difficulty_preference", "adaptive"),
            feedback_frequency=data.get("feedback_frequency", "normal"),
            motivation_style=data.get("motivation_style", "encouragement"),
            language_preference=data.get("language_preference", "zh-CN")
        )


@dataclass
class SRLProfile:
    """自我调节学习(SRL)档案"""
    current_level: SRLLevel = SRLLevel.BEGINNER
    goal_setting_score: float = 0.0        # 目标设定能力评分 (0-100)
    planning_score: float = 0.0            # 计划制定能力评分 (0-100)
    monitoring_score: float = 0.0          # 自我监控能力评分 (0-100)
    evaluation_score: float = 0.0          # 自我评估能力评分 (0-100)
    reflection_score: float = 0.0          # 反思能力评分 (0-100)
    strategy_use_score: float = 0.0        # 策略使用能力评分 (0-100)
    motivation_regulation_score: float = 0.0  # 动机调节能力评分 (0-100)
    last_assessment_date: Optional[datetime] = None
    assessment_history: List[Dict[str, Any]] = field(default_factory=list)
    
    @property
    def overall_srl_score(self) -> float:
        """计算总体SRL评分"""
        scores = [
            self.goal_setting_score,
            self.planning_score,
            self.monitoring_score,
            self.evaluation_score,
            self.reflection_score,
            self.strategy_use_score,
            self.motivation_regulation_score
        ]
        return sum(scores) / len(scores) if scores else 0.0
    
    def update_level_based_on_score(self):
        """根据评分更新SRL水平"""
        overall_score = self.overall_srl_score
        if overall_score >= 80:
            self.current_level = SRLLevel.ADVANCED
        elif overall_score >= 60:
            self.current_level = SRLLevel.PROFICIENT
        elif overall_score >= 40:
            self.current_level = SRLLevel.DEVELOPING
        else:
            self.current_level = SRLLevel.BEGINNER
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            "current_level": self.current_level.value,
            "goal_setting_score": self.goal_setting_score,
            "planning_score": self.planning_score,
            "monitoring_score": self.monitoring_score,
            "evaluation_score": self.evaluation_score,
            "reflection_score": self.reflection_score,
            "strategy_use_score": self.strategy_use_score,
            "motivation_regulation_score": self.motivation_regulation_score,
            "overall_srl_score": self.overall_srl_score,
            "last_assessment_date": self.last_assessment_date.isoformat() if self.last_assessment_date else None,
            "assessment_history": self.assessment_history
        }
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'SRLProfile':
        """从字典创建实例"""
        instance = cls(
            current_level=SRLLevel(data.get("current_level", SRLLevel.BEGINNER.value)),
            goal_setting_score=data.get("goal_setting_score", 0.0),
            planning_score=data.get("planning_score", 0.0),
            monitoring_score=data.get("monitoring_score", 0.0),
            evaluation_score=data.get("evaluation_score", 0.0),
            reflection_score=data.get("reflection_score", 0.0),
            strategy_use_score=data.get("strategy_use_score", 0.0),
            motivation_regulation_score=data.get("motivation_regulation_score", 0.0),
            assessment_history=data.get("assessment_history", [])
        )
        
        # 处理日期字段
        if data.get("last_assessment_date"):
            try:
                instance.last_assessment_date = datetime.fromisoformat(data["last_assessment_date"])
            except ValueError:
                instance.last_assessment_date = None
        
        return instance


@dataclass
class Child(BaseUser):
    """儿童用户模型"""
    id: str = field(default_factory=lambda: f"child_{uuid.uuid4().hex[:8]}")
    name: str = ""
    age: Optional[int] = None
    grade: Optional[Grade] = None
    learning_style: LearningStyle = LearningStyle.MULTIMODAL
    srl_level: SRLLevel = SRLLevel.BEGINNER
    srl_profile: SRLProfile = field(default_factory=SRLProfile)
    learning_preferences: LearningPreferences = field(default_factory=LearningPreferences)
    parent_ids: List[str] = field(default_factory=list)
    teacher_ids: List[str] = field(default_factory=list)
    created_at: datetime = field(default_factory=datetime.now)
    updated_at: datetime = field(default_factory=datetime.now)
    is_active: bool = True
    avatar_url: Optional[str] = None
    notes: str = ""

    # 学习统计数据
    total_study_time_minutes: int = 0
    total_sessions: int = 0
    current_streak_days: int = 0
    longest_streak_days: int = 0

    # 六大任务模块进度
    reading_aloud_level: int = 1        # 朗读水平 (1-10)
    reading_comprehension_level: int = 1 # 阅读理解水平 (1-10)
    memorization_level: int = 1         # 背诵水平 (1-10)
    dictation_level: int = 1            # 听写水平 (1-10)
    writing_level: int = 1              # 写作水平 (1-10)
    copying_level: int = 1              # 抄写水平 (1-10)

    def __post_init__(self):
        """初始化后处理"""
        if self.age and not self.grade:
            # 根据年龄自动推断年级
            self.grade = self._infer_grade_from_age(self.age)

        # 确保SRL档案与当前水平同步
        if self.srl_profile.current_level != self.srl_level:
            self.srl_profile.current_level = self.srl_level

    def _infer_grade_from_age(self, age: int) -> Optional[Grade]:
        """根据年龄推断年级"""
        grade_mapping = {
            5: Grade.PRESCHOOL,
            6: Grade.GRADE_1,
            7: Grade.GRADE_2,
            8: Grade.GRADE_3,
            9: Grade.GRADE_4,
            10: Grade.GRADE_5,
            11: Grade.GRADE_6,
            12: Grade.GRADE_7,
            13: Grade.GRADE_8,
            14: Grade.GRADE_9,
        }
        return grade_mapping.get(age)

    def update_srl_level(self):
        """更新SRL水平"""
        self.srl_profile.update_level_based_on_score()
        self.srl_level = self.srl_profile.current_level
        self.updated_at = datetime.now()

    def add_study_session(self, duration_minutes: int):
        """添加学习会话记录"""
        self.total_study_time_minutes += duration_minutes
        self.total_sessions += 1
        self.updated_at = datetime.now()

    def update_task_level(self, task_type: str, new_level: int):
        """更新任务模块水平"""
        if not (1 <= new_level <= 10):
            raise ValueError("任务水平必须在1-10之间")

        task_mapping = {
            "reading_aloud": "reading_aloud_level",
            "reading_comprehension": "reading_comprehension_level",
            "memorization": "memorization_level",
            "dictation": "dictation_level",
            "writing": "writing_level",
            "copying": "copying_level"
        }

        if task_type in task_mapping:
            setattr(self, task_mapping[task_type], new_level)
            self.update_timestamp()
        else:
            raise ValueError(f"未知的任务类型: {task_type}")

    # ==================== BaseUser抽象方法实现 ====================

    def get_id(self) -> str:
        """获取用户唯一标识符"""
        return self.id

    def get_name(self) -> str:
        """获取用户姓名"""
        return self.name

    def get_role(self) -> UserRole:
        """获取用户角色"""
        return UserRole.CHILD

    def get_created_at(self) -> datetime:
        """获取创建时间"""
        return self.created_at

    def get_updated_at(self) -> datetime:
        """获取最后更新时间"""
        return self.updated_at

    def get_is_active(self) -> bool:
        """获取是否为活跃用户"""
        return self.is_active

    @property
    def role(self) -> UserRole:
        """用户角色（向后兼容属性）"""
        return self.get_role()

    def validate(self) -> bool:
        """验证儿童用户数据的有效性"""
        from ..utils.validators import ValidationError

        # 验证必要字段
        if not self.name.strip():
            raise ValidationError("儿童姓名不能为空")

        # 验证年龄范围
        if self.age is not None and (self.age < 3 or self.age > 18):
            raise ValidationError("儿童年龄必须在3-18岁之间")

        # 验证ID格式
        if not self.id or not self.id.startswith("child_"):
            raise ValidationError("儿童用户ID格式不正确")

        # 验证评分范围
        srl_scores = [
            self.srl_profile.goal_setting_score,
            self.srl_profile.planning_score,
            self.srl_profile.monitoring_score,
            self.srl_profile.evaluation_score,
            self.srl_profile.reflection_score,
            self.srl_profile.strategy_use_score,
            self.srl_profile.motivation_regulation_score
        ]

        for score in srl_scores:
            if not (0 <= score <= 100):
                raise ValidationError("SRL评分必须在0-100之间")

        # 验证任务水平
        task_levels = [
            self.reading_aloud_level,
            self.reading_comprehension_level,
            self.memorization_level,
            self.dictation_level,
            self.writing_level,
            self.copying_level
        ]

        for level in task_levels:
            if not (1 <= level <= 10):
                raise ValidationError("任务水平必须在1-10之间")

        return True

    def update_timestamp(self):
        """更新最后修改时间戳"""
        self.updated_at = datetime.now()

    @property
    def average_task_level(self) -> float:
        """计算六大任务的平均水平"""
        levels = [
            self.reading_aloud_level,
            self.reading_comprehension_level,
            self.memorization_level,
            self.dictation_level,
            self.writing_level,
            self.copying_level
        ]
        return sum(levels) / len(levels)

    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            "id": self.id,
            "name": self.name,
            "age": self.age,
            "grade": self.grade.value if self.grade else None,
            "learning_style": self.learning_style.value,
            "srl_level": self.srl_level.value,
            "srl_profile": self.srl_profile.to_dict(),
            "learning_preferences": self.learning_preferences.to_dict(),
            "parent_ids": self.parent_ids,
            "teacher_ids": self.teacher_ids,
            "created_at": self.created_at.isoformat(),
            "updated_at": self.updated_at.isoformat(),
            "is_active": self.is_active,
            "avatar_url": self.avatar_url,
            "notes": self.notes,
            "total_study_time_minutes": self.total_study_time_minutes,
            "total_sessions": self.total_sessions,
            "current_streak_days": self.current_streak_days,
            "longest_streak_days": self.longest_streak_days,
            "reading_aloud_level": self.reading_aloud_level,
            "reading_comprehension_level": self.reading_comprehension_level,
            "memorization_level": self.memorization_level,
            "dictation_level": self.dictation_level,
            "writing_level": self.writing_level,
            "copying_level": self.copying_level,
            "average_task_level": self.average_task_level
        }

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'Child':
        """从字典创建实例"""
        # 处理枚举字段
        grade = Grade(data["grade"]) if data.get("grade") else None
        learning_style = LearningStyle(data.get("learning_style", LearningStyle.MULTIMODAL.value))
        srl_level = SRLLevel(data.get("srl_level", SRLLevel.BEGINNER.value))

        # 处理复杂对象
        srl_profile = SRLProfile.from_dict(data.get("srl_profile", {}))
        learning_preferences = LearningPreferences.from_dict(data.get("learning_preferences", {}))

        # 处理日期字段
        created_at = datetime.fromisoformat(data["created_at"]) if data.get("created_at") else datetime.now()
        updated_at = datetime.fromisoformat(data["updated_at"]) if data.get("updated_at") else datetime.now()

        return cls(
            id=data.get("id", f"child_{uuid.uuid4().hex[:8]}"),
            name=data.get("name", ""),
            age=data.get("age"),
            grade=grade,
            learning_style=learning_style,
            srl_level=srl_level,
            srl_profile=srl_profile,
            learning_preferences=learning_preferences,
            parent_ids=data.get("parent_ids", []),
            teacher_ids=data.get("teacher_ids", []),
            created_at=created_at,
            updated_at=updated_at,
            is_active=data.get("is_active", True),
            avatar_url=data.get("avatar_url"),
            notes=data.get("notes", ""),
            total_study_time_minutes=data.get("total_study_time_minutes", 0),
            total_sessions=data.get("total_sessions", 0),
            current_streak_days=data.get("current_streak_days", 0),
            longest_streak_days=data.get("longest_streak_days", 0),
            reading_aloud_level=data.get("reading_aloud_level", 1),
            reading_comprehension_level=data.get("reading_comprehension_level", 1),
            memorization_level=data.get("memorization_level", 1),
            dictation_level=data.get("dictation_level", 1),
            writing_level=data.get("writing_level", 1),
            copying_level=data.get("copying_level", 1)
        )


@dataclass
class ParentalSettings:
    """家长控制设置"""
    daily_time_limit_minutes: int = 120     # 每日学习时间限制（分钟）
    session_time_limit_minutes: int = 60    # 单次会话时间限制（分钟）
    allowed_study_hours: List[int] = field(default_factory=lambda: list(range(8, 21)))  # 允许学习的小时范围
    content_filter_level: str = "medium"    # 内容过滤级别：low, medium, high
    notification_enabled: bool = True       # 是否启用通知
    progress_report_frequency: str = "weekly"  # 进度报告频率：daily, weekly, monthly
    emergency_contact_enabled: bool = True  # 是否启用紧急联系
    data_sharing_consent: bool = False      # 数据分享同意

    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            "daily_time_limit_minutes": self.daily_time_limit_minutes,
            "session_time_limit_minutes": self.session_time_limit_minutes,
            "allowed_study_hours": self.allowed_study_hours,
            "content_filter_level": self.content_filter_level,
            "notification_enabled": self.notification_enabled,
            "progress_report_frequency": self.progress_report_frequency,
            "emergency_contact_enabled": self.emergency_contact_enabled,
            "data_sharing_consent": self.data_sharing_consent
        }

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'ParentalSettings':
        """从字典创建实例"""
        return cls(
            daily_time_limit_minutes=data.get("daily_time_limit_minutes", 120),
            session_time_limit_minutes=data.get("session_time_limit_minutes", 60),
            allowed_study_hours=data.get("allowed_study_hours", list(range(8, 21))),
            content_filter_level=data.get("content_filter_level", "medium"),
            notification_enabled=data.get("notification_enabled", True),
            progress_report_frequency=data.get("progress_report_frequency", "weekly"),
            emergency_contact_enabled=data.get("emergency_contact_enabled", True),
            data_sharing_consent=data.get("data_sharing_consent", False)
        )


@dataclass
class Parent(BaseUser):
    """家长用户模型"""
    id: str = field(default_factory=lambda: f"parent_{uuid.uuid4().hex[:8]}")
    name: str = ""
    email: str = ""
    phone: Optional[str] = None
    children_ids: List[str] = field(default_factory=list)
    parental_settings: ParentalSettings = field(default_factory=ParentalSettings)
    created_at: datetime = field(default_factory=datetime.now)
    updated_at: datetime = field(default_factory=datetime.now)
    last_login_at: Optional[datetime] = None
    is_active: bool = True
    is_verified: bool = False           # 是否已验证身份
    verification_method: Optional[str] = None  # 验证方式
    avatar_url: Optional[str] = None
    timezone: str = "Asia/Shanghai"
    language_preference: str = "zh-CN"

    # 关系信息
    relationship_to_children: Dict[str, str] = field(default_factory=dict)  # child_id -> relationship
    emergency_contacts: List[Dict[str, str]] = field(default_factory=list)

    def add_child(self, child_id: str, relationship: str = "parent"):
        """添加子女"""
        if child_id not in self.children_ids:
            self.children_ids.append(child_id)
            self.relationship_to_children[child_id] = relationship
            self.update_timestamp()

    def remove_child(self, child_id: str):
        """移除子女"""
        if child_id in self.children_ids:
            self.children_ids.remove(child_id)
            self.relationship_to_children.pop(child_id, None)
            self.update_timestamp()

    def update_settings(self, **kwargs):
        """更新家长设置"""
        for key, value in kwargs.items():
            if hasattr(self.parental_settings, key):
                setattr(self.parental_settings, key, value)
        self.update_timestamp()

    def add_emergency_contact(self, name: str, phone: str, relationship: str = "emergency"):
        """添加紧急联系人"""
        contact = {
            "name": name,
            "phone": phone,
            "relationship": relationship,
            "added_at": datetime.now().isoformat()
        }
        self.emergency_contacts.append(contact)
        self.update_timestamp()

    def verify_identity(self, method: str = "email"):
        """验证身份"""
        self.is_verified = True
        self.verification_method = method
        self.update_timestamp()

    def update_last_login(self):
        """更新最后登录时间"""
        self.last_login_at = datetime.now()
        self.update_timestamp()

    # ==================== BaseUser抽象方法实现 ====================

    def get_id(self) -> str:
        """获取用户唯一标识符"""
        return self.id

    def get_name(self) -> str:
        """获取用户姓名"""
        return self.name

    def get_role(self) -> UserRole:
        """获取用户角色"""
        return UserRole.PARENT

    def get_created_at(self) -> datetime:
        """获取创建时间"""
        return self.created_at

    def get_updated_at(self) -> datetime:
        """获取最后更新时间"""
        return self.updated_at

    def get_is_active(self) -> bool:
        """获取是否为活跃用户"""
        return self.is_active

    @property
    def role(self) -> UserRole:
        """用户角色（向后兼容属性）"""
        return self.get_role()

    def validate(self) -> bool:
        """验证家长用户数据的有效性"""
        from ..utils.validators import ValidationError, validate_email

        # 验证必要字段
        if not self.name.strip():
            raise ValidationError("家长姓名不能为空")

        # 验证邮箱格式
        if self.email and not validate_email(self.email):
            raise ValidationError("邮箱格式不正确")

        # 验证ID格式
        if not self.id or not self.id.startswith("parent_"):
            raise ValidationError("家长用户ID格式不正确")

        # 验证手机号格式（如果提供）
        if self.phone:
            import re
            phone_pattern = r'^1[3-9]\d{9}$'  # 简单的中国手机号验证
            if not re.match(phone_pattern, self.phone):
                raise ValidationError("手机号格式不正确")

        # 验证时区
        valid_timezones = ["Asia/Shanghai", "Asia/Beijing", "UTC", "America/New_York", "Europe/London"]
        if self.timezone not in valid_timezones:
            raise ValidationError("不支持的时区")

        # 验证语言偏好
        valid_languages = ["zh-CN", "zh-TW", "en-US", "en-GB"]
        if self.language_preference not in valid_languages:
            raise ValidationError("不支持的语言偏好")

        return True

    def update_timestamp(self):
        """更新最后修改时间戳"""
        self.updated_at = datetime.now()

    @property
    def children_count(self) -> int:
        """子女数量"""
        return len(self.children_ids)

    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            "id": self.id,
            "name": self.name,
            "email": self.email,
            "phone": self.phone,
            "children_ids": self.children_ids,
            "children_count": self.children_count,
            "parental_settings": self.parental_settings.to_dict(),
            "created_at": self.created_at.isoformat(),
            "updated_at": self.updated_at.isoformat(),
            "last_login_at": self.last_login_at.isoformat() if self.last_login_at else None,
            "is_active": self.is_active,
            "is_verified": self.is_verified,
            "verification_method": self.verification_method,
            "avatar_url": self.avatar_url,
            "timezone": self.timezone,
            "language_preference": self.language_preference,
            "relationship_to_children": self.relationship_to_children,
            "emergency_contacts": self.emergency_contacts
        }

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'Parent':
        """从字典创建实例"""
        # 处理复杂对象
        parental_settings = ParentalSettings.from_dict(data.get("parental_settings", {}))

        # 处理日期字段
        created_at = datetime.fromisoformat(data["created_at"]) if data.get("created_at") else datetime.now()
        updated_at = datetime.fromisoformat(data["updated_at"]) if data.get("updated_at") else datetime.now()
        last_login_at = None
        if data.get("last_login_at"):
            try:
                last_login_at = datetime.fromisoformat(data["last_login_at"])
            except ValueError:
                last_login_at = None

        return cls(
            id=data.get("id", f"parent_{uuid.uuid4().hex[:8]}"),
            name=data.get("name", ""),
            email=data.get("email", ""),
            phone=data.get("phone"),
            children_ids=data.get("children_ids", []),
            parental_settings=parental_settings,
            created_at=created_at,
            updated_at=updated_at,
            last_login_at=last_login_at,
            is_active=data.get("is_active", True),
            is_verified=data.get("is_verified", False),
            verification_method=data.get("verification_method"),
            avatar_url=data.get("avatar_url"),
            timezone=data.get("timezone", "Asia/Shanghai"),
            language_preference=data.get("language_preference", "zh-CN"),
            relationship_to_children=data.get("relationship_to_children", {}),
            emergency_contacts=data.get("emergency_contacts", [])
        )
